<template>
  <div class="route_manager">
    <div class="route_day_layout">
      <div class="title"><b>行程列表</b></div>
      <ul id="route_day" class="route_day">
        <li v-for="item in routeData.value" :key="item.tempId" :class="{ active: item.tempId == curDay.value.tempId }"
          @click="switchDay(item)">
          <div class="day_li">
            <span>第{{ item.dayNum }}天</span>
            <el-icon class="move" :size="18" v-if="readOnly == false">
              <Rank />
            </el-icon>
          </div>

          <div class="del" @click.stop="delDay(item.tempId)" v-if="readOnly == false">
            <el-icon>
              <Close />
            </el-icon>
          </div>
        </li>
      </ul>
      <div class="dashed_but" @click="addRouteDay" v-if="readOnly == false">
        <el-icon>
          <Plus />
        </el-icon>
        <span>添加行程</span>
      </div>
    </div>
    <div class="route_details_layout">
      <div class="route_details_title">
        <b>第{{ curDay.value.dayNum }}天</b>
        <el-input class="details_title_input" v-model="curDay.value.title" placeholder="请输入行程标题" :clearable="true"
          :disabled="readOnly" />
      </div>

      <DynamicParams ref="routeDetailsView" :data="curDay.value.detailItems" :template="template"
        :operation="operation(readOnly)" :multipleType="true" typeProp="detailType" customAdd :type1Code="type1"
        :type2Code="type2" :type3Code="type3" :showDefault="false" :multipleAddText="['添加活动', '添加住宿安排', '添加景点']">
        <el-table-column label="活动类容" align="center">
          <template #default="scope">
            <el-input class="m_b_10" v-model="scope.row.detailTitle" placeholder="请输入活动标题" :clearable="true" :disabled="readOnly" />
            <el-input v-if="scope.row.detailType == type3" class="m_b_10" v-model="scope.row.description"
              placeholder="请输入景点描述" :rows="4" type="textarea"  :clearable="true" :disabled="readOnly" />
            <div v-if="scope.row.detailType == type1">
              <el-input v-model="scope.row.intro" :rows="8" type="textarea" placeholder="请输入活动描述" :clearable="true"
              :disabled="readOnly" />
            </div>
            <div v-else-if="scope.row.detailType == type2">
              <div class="travel_programme" v-for="item in scope.row.hotelItems" :key="item.id">
                <b>{{ item.packageName }}:</b>
                <div class="programme_room" v-if="$.isNull(item.hotelCode)">
                  <span>尚未设置</span>
                  <el-button size="small" type="primary" text @click="bindRoom(item)" :disabled="readOnly">
                    绑定房型
                  </el-button>
                </div>
                <div class="programme_room" v-else>
                  <span>{{ item.hotelName }}-{{ item.roomName }}</span>
                  <el-button size="small" type="primary" text @click="bindRoom(item)" :disabled="readOnly">
                    修改绑定
                  </el-button>
                </div>
              </div>
            </div>
            <div v-else-if="scope.row.detailType == type3">
              <UploadPicture v-model="scope.row.picUrl" :limit="10" :imgSize="$.describeImgSize()"
                :fileSize="$.imgFileSize()" :disabled="readOnly" />
            </div>
          </template>
        </el-table-column>

        <el-table-column label="开始时间" align="center" :width="130">
          <template #default="scope">
            <el-input :prefix-icon="Calendar" placeholder="例 16:30" v-model="scope.row.startTime" />
            <!-- <el-time-picker v-model="scope.row.startTime" format="HH:mm" value-format="HH:mm" placeholder="选择时间"
              :disabled="readOnly" /> -->
          </template>
        </el-table-column>
      </DynamicParams>
      <HotelSelect v-if="!readOnly" title="绑定房型" ref="hotelSelect" @select="roomSelect" />
    </div>
  </div>
  <!-- <div @click="aaaa">aaa</div> -->
</template>

<script setup>
import DynamicParams from "@com/DynamicParams.vue";
import HotelSelect from "@com/HotelSelect.vue";
import {
  defineProps,
  reactive,
  ref,
  defineExpose,
  onMounted,
  watch,
} from "vue";
import Sortable from "sortablejs";
import $ from "@util/base";
import { $msg } from "@/common/ui/msg";
import UploadPicture from "../upload/UploadPicture.vue";
import { Calendar } from "@element-plus/icons-vue";

const props = defineProps({
  data: { type: Array, default: () => [] },
  readOnly: { type: Boolean, default: false },
  travelProgramme: { type: Array },
});
const type1 = "1008001";
const type2 = "1008002";
const type3 = "1008003";
const template = {
  detailType: null,
  detailTitle: null,
  startTime: null,
  hotelItems: props.travelProgramme,
};

function aaaa() {
  console.log(getValue());
}

watch(
  () => props.data,
  (val) => {
    if ($.isNotEmpty(val)) {
      routeData.value = initData();
      sortData.value = routeData.value;
      curDay.value = val[0];
      lastDay = val[0];
    }
  }
);

watch(
  () => props.travelProgramme,
  (val) => {
    template.hotelItems = $.deepCopy(val);
  }
);

const routeData = reactive({ value: initData() });

function operation(readOnly) {
  if (readOnly) {
    return {
      move: false,
      modify: false,
      del: false,
      add: true,
      check: false,
    };
  } else {
    return {
      move: true,
      modify: false,
      del: true,
      add: false,
      check: false,
    };
  }
}

function initData() {
  if ($.isNotEmpty(props.data)) {
    return props.data.map((e) => {
      e.tempId = $.uuid8();
      return e;
    });
  } else {
    return [];
  }
}
if ($.isEmpty(props.data)) {
  addRouteDay();
}

const routeDetailsView = ref(null);
const hotelSelect = ref(null);

var bindRoomTarget;
function bindRoom(data) {
  bindRoomTarget = data;
  hotelSelect.value.open();
}

function roomSelect(data) {
  bindRoomTarget.hotelName = data.hotelName;
  bindRoomTarget.roomName = data.hotelRoomName;
  bindRoomTarget.hotelCode = data.hotelCode;
  bindRoomTarget.roomCode = data.hotelRoomCode;
}

function delDay(id) {
  routeData.value.remove((e) => {
    return e.tempId === id;
  });
  if (id == curDay.value.tempId) {
    if (routeData.value.length > 0) {
      curDay.value = routeData.value[0];
    } else {
      curDay.value = [];
    }
  }
  routeData.value.map((e, i) => {
    e.dayNum = i + 1;
  });
}

function addRouteDay() {
  let template = {
    title: null,
    dayNum: routeData.value.length + 1,
    tempId: $.uuid8(),
    detailItems: [],
  };
  routeData.value.push(template);
}

var curDay = reactive({ value: routeData.value[0] });
var lastDay = routeData.value[0];

function switchDay(data) {
  if (data.tempId != curDay.value.tempId) {
    let routeDetails = routeDetailsView.value.getValue();
    //检查routeDetails数据完整性，是否可以切换天数
    if (check(curDay.value, routeDetails)) {
      //routeDetails数据保证在天数中
      lastDay.detailItems = routeDetails;
      //切换当前天
      curDay.value = data;
      //记录上次天
      lastDay = data;
    }
  }
}

function check(day, routeDetails) {
  console.log(routeDetails)
  // if ($.isEmpty(day.title)) {
  //   $msg.error("请填写第" + day.dayNum + "天行程标题")
  //   return false
  // }
  if ($.isEmpty(routeDetails)) {
    $msg.error("请设置第" + day.dayNum + "天行程详情");
    return false;
  }
  for (const item of routeDetails) {
    if ($.isEmpty(item.detailTitle)) {
      $msg.error("请填行程安排写活动标题");
      return false;
    }
    // if ($.isEmpty(item.startTime)) {
    //   $msg.error("请选择行程安排开始时间");
    //   return false;
    // }
    if (item.detailType == type1) {
      if ($.isEmpty(item.intro)) {
        $msg.error("请填写行程安排活动描述");
        return false;
      }
    } else if (item.detailType == type2) {
      for (const programme of item.hotelItems) {
        if ($.isNull(programme.roomCode)) {
          $msg.error("请填绑定行程安排房间");
          return false;
        }
      }
    } else if (item.detailType == type3) {
      if ($.isEmpty(item.detailTitle)) {
        $msg.error("请填写景点标题");
        return false;
      }
      if ($.isEmpty(item.description)) {
        $msg.error("请填写景点说明");
        return false;
      }
      if (!(item.picUrl != null && item.picUrl.length > 0)) {
        $msg.error("请设置图片");
        return false;
      }
    }
  }
  return true;
}

const sortData = reactive({ value: routeData.value });
onMounted(() => {
  if (!props.readOnly) {
    const ul = document.querySelector("#route_day");
    Sortable.create(ul, {
      handle: ".move",
      animation: 150,
      onEnd: function (evt) {
        const currRow = sortData.value.splice(evt.oldIndex, 1)[0];
        sortData.value.splice(evt.newIndex, 0, currRow);
        routeData.value.map((e, i) => {
          e.dayNum = i + 1;
        });
      },
    });
  }
});

function handerData(routeData) {
  for (const day of routeData) {
    delete day.tempId;
    for (const details of day.detailItems) {
      delete details.tempId;
      if (details.detailType == type1) {
        delete details.hotelItems;
      }
    }
  }
  return routeData;
}

function getValue() {
  let routeDetails = routeDetailsView.value.getValue();
  if ($.isEmpty(routeDetails)) {
    return null;
  }
  if (check(curDay.value, routeDetails)) {
    curDay.value.detailItems = routeDetails;
    lastDay = curDay.value;
    return handerData($.deepCopy(routeData.value));
  } else {
    return false;
  }
}

defineExpose({ getValue });
</script>
<style lang="scss">
.route_manager {
  display: flex;
  border: 1px solid $border;

  .route_day_layout {
    display: flex;
    flex-direction: column;
    width: 180px;
    border-right: 1px solid $border;

    .active {
      background-color: $primary;
      color: #fff;
    }

    ul {
      list-style-type: none;
    }

    ul>li {
      color: #333;
      cursor: pointer;
      padding: 10px;
      margin: 10px;
      background-color: #f1f1f1;
      position: relative;
      border-radius: 2px;

      &:hover {
        .del {
          display: block;
        }
      }
    }

    .day_li {
      display: flex;
      align-items: center;
      padding-right: 10px;
      min-width: 85px;
      justify-content: space-between;
    }

    .del {
      display: none;
      cursor: pointer;
      top: -6px;
      right: -6px;
      background-color: #fc443e;
      color: #fff;
      position: absolute;
      width: 20px;
      height: 20px;
      line-height: 26px;
      text-align: center;
      border-radius: 50%;
    }

    .dashed_but {
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 5px;

      span {
        margin-left: 2px;
      }
    }
  }

  .title {
    width: 100%;
    text-align: center;
    height: 55px;
    padding: 0;
    line-height: 55px;
    border-bottom: 1px solid $border;
    margin-bottom: 15px;
  }

  .route_details_layout {
    padding: 0 20px;
    width: 100%;

    .route_details_title {
      display: flex;
      align-items: center;
      height: 55px;

      b {
        margin-right: 10px;
      }

      .details_title_input {
        width: 240px;
      }
    }

    .el-input__inner {
      width: 60px;
    }
  }

  .m_b_10 {
    margin-bottom: 10px;
  }

  .travel_programme {
    text-align: left;

    margin-top: 10px;
  }

  .programme_room {
    margin-top: 5px;
    padding: 6px 8px;
    background-color: #f2f2f2;
    display: flex;
    justify-content: space-between;
  }
}
</style>